package com.cookie.aivoiceapp.service

import android.app.Service
import android.content.Intent
import android.os.Handler
import android.os.IBinder
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.lottie.LottieAnimationView
import com.cookie.aivoiceapp.R
import com.cookie.aivoiceapp.adapter.ChatListAdapter
import com.cookie.aivoiceapp.data.ChatList
import com.cookie.aivoiceapp.entity.AppConstants
import com.cookie.lib_base.helper.*
import com.cookie.lib_base.helper.`fun`.AppHelper
import com.cookie.lib_base.helper.`fun`.CommonSettingHelper
import com.cookie.lib_base.helper.`fun`.ContactHelper
import com.cookie.lib_base.util.L
import com.cookie.lib_network.HttpManager
import com.cookie.lib_network.bean.JokeOneData
import com.cookie.lib_network.bean.RobotData
import com.cookie.lib_voice.engine.VoiceEngineAnalyze
import com.cookie.lib_voice.impl.OnAsrResultListener
import com.cookie.lib_voice.impl.OnNluResultListener
import com.cookie.lib_voice.manager.VoiceManager
import com.cookie.lib_voice.tts.VoiceTTS
import com.cookie.lib_voice.words.WordsTools
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 *   文件名:    VoiceService
 *   创建者:    cookie
 *   创建时间:   2020/10/13 14:03
 *   描述:      语音服务
 */
class VoiceService : Service(), OnNluResultListener {

    private val mHandler = Handler()
    private lateinit var mFullWindowView: View
    private lateinit var mChatListView: RecyclerView
    private lateinit var mLottieView: LottieAnimationView
    private lateinit var tvVoiceTips: TextView
    private val mList = ArrayList<ChatList>()
    private lateinit var mChatAdapter: ChatListAdapter

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onCreate() {
        super.onCreate()
        L.i("语音服务启动")
        initCoreVoiceService()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        bindNotification()
        return START_STICKY_COMPATIBILITY
    }

    //绑定通知栏
    private fun bindNotification() {
        startForeground(1000, NotificationHelper.bindVoiceService("正在运行"))
    }

    //初始化语音服务
    private fun initCoreVoiceService() {

        WindowHelper.initHelper(this)
        mFullWindowView = WindowHelper.getView(R.layout.layout_window_item)
        mChatListView = mFullWindowView.findViewById<RecyclerView>(R.id.mChatListView)
        mLottieView = mFullWindowView.findViewById<LottieAnimationView>(R.id.mLottieView)
        tvVoiceTips = mFullWindowView.findViewById<TextView>(R.id.tvVoiceTips)
        mChatListView.layoutManager = LinearLayoutManager(this)
        mChatAdapter = ChatListAdapter(mList)
        mChatListView.adapter = mChatAdapter

        VoiceManager.initManager(this, object : OnAsrResultListener {

            override fun wakeUpReady() {
                L.i("唤醒准备就绪")
                addAiText("唤醒引擎准备就绪")
            }

            override fun asrStartSpeak() {
                L.i("开始说话")
            }

            override fun asrStopSpeak() {
                L.i("结束说话")
            }

            override fun wakeUpSuccess(result: JSONObject) {
                L.i("唤醒成功: $result")
                val errorCode = result.optInt("errorCode")
                if (errorCode == 0) {
                    //唤醒成功
                    val word = result.optString("word")
                    if (word == "小杜小杜") {
                        wakeUpFix()
                    }
                }
            }

            override fun updateUserText(text: String) {
                updateTips(text)
            }

            override fun asrResult(result: JSONObject) {
                L.i("===========================RESULT===========================")
                L.i("result: $result")
            }

            override fun nluResult(nlu: JSONObject) {
                L.i("===========================NLU===========================")
                L.i("nlu: $nlu")
                addMineText(nlu.optString("raw_text"))
                VoiceEngineAnalyze.analyzeNlu(nlu, this@VoiceService)
            }

            override fun voiceError(text: String) {
                L.e("发生错误: $text")
                hideWindow()
            }
        })
    }

    //唤醒成功之后的操作
    private fun wakeUpFix() {
        showWindow()
        updateTips("正在聆听...")
        SoundPoolHelper.play(R.raw.record_start)
        //应答
        val weakUpText = WordsTools.weakUpWords()
        addAiText(weakUpText, object : VoiceTTS.OnTTSResultListener {
            override fun ttsEnd() {
                //开始识别
                VoiceManager.startAsr()
            }
        })
    }

    //显示窗口
    private fun showWindow() {
        L.i("=====显示窗口=====")
        mLottieView.playAnimation()
        WindowHelper.show(mFullWindowView)
    }

    //隐藏窗口
    private fun hideWindow() {
        L.i("=====隐藏窗口=====")
        mHandler.postDelayed({
            WindowHelper.hide(mFullWindowView)
            mLottieView.pauseAnimation()
        }, 2 * 1000)
    }

    override fun openApp(appName: String) {
        if (!TextUtils.isEmpty(appName)) {
            val isOpen = AppHelper.launcherApp(appName)
            if (isOpen) {
                addAiText("正在为你打开$appName")
            } else {
                addAiText("很抱歉，无法为你打开$appName")
            }
        }
        hideWindow()
    }

    //卸载App
    override fun unInstallApp(appName: String) {
        if (!TextUtils.isEmpty(appName)) {
            val isUninstall = AppHelper.unInstallApp(appName)
            if (isUninstall) {
                addAiText("正在为你卸载$appName")
            } else {
                addAiText("很抱歉，无法为你卸载$appName")
            }
        }
        hideWindow()
    }

    //其他APP
    override fun otherApp(appName: String) {
        //全部跳转应用市场
        if (!TextUtils.isEmpty(appName)) {
            val isIntent = AppHelper.launcherAppStore(appName)
            if (isIntent) {
                addAiText("正在操作$appName")
            } else {
                addAiText(WordsTools.noAnswerWords())
            }
        }
        hideWindow()
    }

    //返回
    override fun back() {
        addAiText("正在为你执行返回操作")
        CommonSettingHelper.back()
        hideWindow()
    }

    //返回首页
    override fun home() {
        addAiText("正在为你回到首页")
        CommonSettingHelper.home()
        hideWindow()
    }

    //音量+
    override fun setVolumeUp() {
        addAiText("正在增加音量")
        CommonSettingHelper.setVolumeUp()
        hideWindow()
    }

    //音量-
    override fun setVolumeDown() {
        addAiText("正在减少音量")
        CommonSettingHelper.setVolumeDown()
        hideWindow()
    }

    //拨打联系人
    override fun callPhoneForName(name: String) {
        val list = ContactHelper.mContactList.filter { it.phoneName == name }
        if (list.isNotEmpty()) {
            addAiText("正在为你拨打$name}", object : VoiceTTS.OnTTSResultListener {
                override fun ttsEnd() {
                    ContactHelper.callPhone(list[0].phoneNumber)
                }
            })
        } else {
            addAiText("抱歉,通讯录中无此联系人")
        }
        hideWindow()
    }

    //拨打号码
    override fun callPhoneForNumber(phone: String) {
        addAiText("正在为你拨打$phone", object : VoiceTTS.OnTTSResultListener {
            override fun ttsEnd() {
                ContactHelper.callPhone(phone)
            }
        })
        hideWindow()
    }

    //播放笑话
    override fun playJoke() {
        HttpManager.queryJoke(object : Callback<JokeOneData> {
            override fun onFailure(call: Call<JokeOneData>, t: Throwable) {
                jokeError()
            }

            override fun onResponse(call: Call<JokeOneData>, response: Response<JokeOneData>) {
                if (response.isSuccessful) {
                    response.body()?.let {
                        if (it.error_code == 0) {
                            //根据result随机抽取一段笑话播放
                            val index = WordsTools.randomInt(it.result.size)
                            if (index < it.result.size) {
                                val data = it.result[index]
                                addAiText(data.content, object : VoiceTTS.OnTTSResultListener {
                                    override fun ttsEnd() {
                                        hideWindow()
                                    }
                                })
                            }
                        } else {
                            jokeError()
                        }
                    }
                } else {
                    jokeError()
                }
            }
        })
    }

    //笑话列表
    override fun jokeList() {
        addAiText("正在为你搜索笑话")
        ARouterHelper.startActivity(ARouterHelper.PATH_JOKE)
        hideWindow()
    }

    //星座时间
    override fun constellTime(name: String) {
        val text = ConstellHelper.getConstellTime(name)
        addAiText(text, object : VoiceTTS.OnTTSResultListener {
            override fun ttsEnd() {
                hideWindow()
            }
        })
    }

    //星座详情
    override fun constellInfo(name: String) {
        addAiText("正在为你查询${name}的详情", object : VoiceTTS.OnTTSResultListener {
            override fun ttsEnd() {
                hideWindow()
            }
        })
        ARouterHelper.startActivity(ARouterHelper.PATH_CONSTELLATION, "name", name)
    }

    //机器人
    override fun aiRobot(text: String) {
        //请求机器人回答
        HttpManager.aiRobotChat(text, object : Callback<RobotData> {

            override fun onFailure(call: Call<RobotData>, t: Throwable) {
                addAiText(WordsTools.noAnswerWords())
                hideWindow()
            }

            override fun onResponse(call: Call<RobotData>, response: Response<RobotData>) {
                if (response.isSuccessful){
                    response.body()?.let {
                        if(it.intent.code == 10004){
                            //回答
                            if (it.results.isEmpty()){
                                addAiText(WordsTools.noAnswerWords())
                                hideWindow()
                            }else{
                                addAiText(it.results[0].values.text)
                                hideWindow()
                            }
                        }else{
                            addAiText(WordsTools.noAnswerWords())
                            hideWindow()
                        }
                    }
                }
            }
        })
    }

    //查询天气
    override fun queryWeather() {
    }

    //无法应答
    override fun nluError() {
        addAiText(WordsTools.noAnswerWords())
        hideWindow()
    }

    //添加我的文本
    private fun addMineText(text: String) {
        val bean = ChatList(AppConstants.TYPE_MINE_TEXT)
        bean.text = text
        baseAddItem(bean)
    }

    //添加AI的文本
    private fun addAiText(text: String) {
        val bean = ChatList(AppConstants.TYPE_AI_TEXT)
        bean.text = text
        baseAddItem(bean)
        VoiceManager.ttsStart(text)
    }

    //添加AI的文本
    private fun addAiText(text: String, mOnTTSResultListener: VoiceTTS.OnTTSResultListener) {
        val bean = ChatList(AppConstants.TYPE_AI_TEXT)
        bean.text = text
        baseAddItem(bean)
        VoiceManager.ttsStart(text, mOnTTSResultListener)
    }


    //添加基类
    private fun baseAddItem(bean: ChatList) {
        mList.add(bean)
        mChatAdapter.notifyItemInserted(mList.size - 1)
    }

    //更新提示语
    private fun updateTips(text: String) {
        tvVoiceTips.text = text
    }

    //笑话错误
    private fun jokeError() {
        hideWindow()
        addAiText("抱歉，未搜索到笑话")
    }
}